package school.valon.business.impl;

import org.springframework.transaction.annotation.Transactional;

import school.valon.business.ValidationRulesBusiness;
import school.valon.business.base.BaseBusiness;
import school.valon.dto.ValidationRulesDto;
import school.valon.persistence.dao.StaffDao;
import school.valon.persistence.dao.ValidationRulesDao;
import school.valon.persistence.pojo.Staff;
import school.valon.persistence.pojo.ValidationRules;

@Transactional
public class ValidationRulesBusinessImpl extends BaseBusiness implements ValidationRulesBusiness {

	private ValidationRulesDao validationRulesDao;
	private StaffDao staffDao;

	public void setValidationRulesDao(ValidationRulesDao validationRulesDao) {
		this.validationRulesDao = validationRulesDao;
	}

	public void setStaffDao(StaffDao staffDao) {
		this.staffDao = staffDao;
	}

	public ValidationRulesDto saveValidationRules(ValidationRulesDto validationRulesDto) {
		ValidationRules validationRules = null;
		if (validationRulesDto.getValidationRulesId() == null) {
			Staff staff = null;
			if (validationRulesDto.getStaff() != null && validationRulesDto.getStaff().getStaffId() != null) {
				staff = staffDao.find(validationRulesDto.getStaff().getStaffId());
			}
			validationRules = mapper.map(validationRulesDto, ValidationRules.class);
			validationRules.setStaff(staff);
			validationRules = validationRulesDao.create(validationRules);
		} else {
			validationRules = validationRulesDao.find(validationRulesDto.getValidationRulesId());
			validationRules.setStartDate(validationRulesDto.getStartDate());
			validationRules.setCreatedOn(validationRulesDto.getCreatedOn());
			validationRules.setEndDate(validationRulesDto.getEndDate());
			validationRules.setPredefinedRules(validationRulesDto.getPredefinedRules());
			validationRules.setValue(validationRulesDto.getValue());
			validationRulesDao.update(validationRules);
		}
		ValidationRulesDto newValidationRulesDto = mapper.map(validationRules, ValidationRulesDto.class);
		newValidationRulesDto.setStaff(null);
		return newValidationRulesDto;
	}

	public void deleteValidationRules(Integer validationRulesId) {
		validationRulesDao.delete(validationRulesId);
	}
}
